<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Postalapi\Postal;
use App\Http\Controllers\ScoreRuleController;
use App\Models\BookHomeOrder;
use App\Models\BookHomeOrderAddress;
use App\Models\BookHomeOrderBook;
use App\Models\BookHomeOrderRefund;
use App\Models\BookHomePostalReturn;
use App\Models\BookHomePostalRev;
use App\Models\BookHomePurchase;
use App\Models\BookHomeReturnAddress;
use App\Models\BookHomeReturnRecord;
use App\Models\BookHomeSchoolbag;
use App\Models\CourierName;
use App\Models\LibBook;
use App\Models\LibBookBarcode;
use App\Models\Manage;
use App\Models\ShopBook;
use App\Models\UserLibraryInfo;
use App\Models\UserWechatInfo;
use App\Validate\BookHomeNewBookValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 图书到家 馆藏书借阅
 * Class LibraryBorrow
 * @package app\api\controller
 */
class BookHomeLibBookController extends CommonController
{

    private $model = null;
    private $bookHomeOrderBookModel = null;
    private $bookHomePurchaseModel = null;
    private $libBookModel = null;
    private $libBookBarcodeModel = null;
    private $validate = null;
    public $score_type = 17;

    public function __construct()
    {
        parent::__construct();
        $this->model = new BookHomeOrder();
        $this->bookHomeOrderBookModel = new BookHomeOrderBook();
        $this->bookHomePurchaseModel = new BookHomePurchase();
        $this->libBookModel = new LibBook();
        $this->libBookBarcodeModel = new LibBookBarcode();
        $this->validate = new BookHomeNewBookValidate();
    }


    /**
     * 申请列表、发货列表、所有订单列表 （馆藏书）
     * @param is_pay  类型  2 已支付  5 .已退款  6.已同意（后台单纯同意）
     *              7 已拒绝（后台单纯同意）  8已发货（数据就增加到用户采购列表）
     *              9 无法发货    固定参数  申请列表 2   发货列表 6  所有订单列表 5789
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param keywords_type 检索key  0 全部 1 订单号 2 读者证号 3 收件人姓名  4 收件人电话
     * @param keywords 检索值
     * @param page  页数默认为 1
     * @param limit  条数 默认 10 条
     */
    public function orderList()
    {
        //处理已失效的订单
        BookHomeOrder::checkNoPayOrder();

        //增加验证场景进行验证
        if (!$this->validate->scene('order_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $is_pay = $this->request->is_pay;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 1) ?: 10;


        // $shop_all_id = $this->getAdminShopIdAll();
        // if (empty($shop_all_id)) {
        //     return $this->returnApi(203, '暂无数据'); //无权限访问
        // }

        $res = $this->model->lists(null, 2, $is_pay, null, $keywords, $keywords_type, $start_time, $end_time, null, $limit);
        if ($res['data']) {
            $bookHomePostalRevModel = new BookHomePostalRev();

            foreach ($res['data'] as $key => $val) {
                //读者证号信息
                $res['data'][$key]['reader_info']['account'] = $val['account'];
                $res['data'][$key]['reader_info']['username'] = $val['username'];
                unset($res['data'][$key]['account'], $res['data'][$key]['username']);

                //    $res['data'][$key]['shop_info']['shop_name'] = $val['shop_name'];
                //  unset($res['data'][$key]['shop_name']);

                $res['data'][$key]['order_info']['id'] = $val['id'];
                $res['data'][$key]['order_info']['is_pay'] = $val['is_pay'];
                $res['data'][$key]['order_info']['order_number'] = $val['order_number'];
                $res['data'][$key]['order_info']['create_time'] = $val['create_time'];
                unset($res['data'][$key]['is_pay'], $res['data'][$key]['order_number'], $res['data'][$key]['create_time'], $res['data'][$key]['id']);

                $shopBookModel = new ShopBook();
                $res['data'][$key]['order_info']['time'] = $shopBookModel->getStateNameAndTime($val)['time']; //各种事件的集合

                $res['data'][$key]['address_info']['tracking_number'] = $val['tracking_number']; //快递单号
                $res['data'][$key]['address_info']['username'] = $val['address_username'];
                $res['data'][$key]['address_info']['tel'] = $val['tel'];
                $res['data'][$key]['address_info']['province'] = $val['province'];
                $res['data'][$key]['address_info']['city'] = $val['city'];
                $res['data'][$key]['address_info']['district'] = $val['district'];
                $res['data'][$key]['address_info']['street'] = $val['street'];
                $res['data'][$key]['address_info']['address'] = $val['address'];
                unset($res['data'][$key]['address_username']);
                unset($res['data'][$key]['tel']);
                unset($res['data'][$key]['province']);
                unset($res['data'][$key]['city']);
                unset($res['data'][$key]['district']);
                unset($res['data'][$key]['street']);
                unset($res['data'][$key]['address']);

                $res['data'][$key]['book_info'] = $this->libBookModel->from($this->libBookModel->getTable() . ' as b')
                    ->select('b.id', 'book_name', 'author', 'press', 'pre_time', 'isbn', 'price', 'l.book_num', 'l.barcode', 'l.cur_local_note')
                    ->rightJoin('lib_book_barcode as l', 'l.book_id', '=', 'b.id')
                    ->rightJoin('book_home_order_book as o', 'o.barcode_id', '=', 'l.id')
                    ->where('o.order_id', $val['id'])
                    ->get()
                    ->toArray();

                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);

                //获取运单轨迹
                if (!empty($val['tracking_number'])) {
                    $res['data'][$key]['track'] = $bookHomePostalRevModel->getTrack($val['tracking_number']);
                } else {
                    $res['data'][$key]['track'] = null;
                }
            }

            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 获取未处理订单 和未发货订单数量 (馆藏书)
     */
    public function getOrderNumber()
    {
        //获取未处理订单数量
        $data['untreated_number'] = $this->model->getOrderNumber(2, 2);
        //获取未发货订单数量
        $data['undeliver_number'] = $this->model->getOrderNumber(2, 6);
        //获取其他订单数量
        $data['other_order_number'] = $this->model->getOrderNumber(2, [5, 7, 8, 9]);

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 获取馆藏书订单详情
     * @param order_id  订单id
     */
    public function orderDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('order_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->order_id);
        if ($res) {
            //获取书籍信息
            $res = $res->toArray();
            $data =  $this->model->checkOrderData($res);
            $data['book_info'] = $this->bookHomeOrderBookModel->getOrderBookInfoList($res['id'], $res);

            //获取运单轨迹
            if (!empty($res['tracking_number'])) {
                $bookHomePostalRevModel = new BookHomePostalRev();
                $data['track'] = $bookHomePostalRevModel->getTrack($res['tracking_number']);
            } else {
                $data['track'] = null;
            }
            $data['payment'] = $res['payment']  == 1 ? "微信支付" : '其他';
            return $this->returnApi(200, '获取成功', true, $data);
        }
        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 打印电子面单 （馆藏书）
     * @param order_id  订单id  只针对单个订单
     */
    public function printExpressSheetLib()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('print_express_sheet_lib')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //获取发货地址信息
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $deliver_address = $bookHomeReturnAddressModel->getDeliverAddress(2);

        $take_address = BookHomeOrderAddress::select('username', 'tel', 'province', 'city', 'district', 'street', 'address')
            ->where('order_id', $this->request->order_id)
            ->first();

        $postalObj = new Postal();
        $print_electronic_sheet_info = $postalObj->printElectronicSheet($this->request->order_id, $deliver_address, $take_address);


        $tracking_number = BookHomeOrder::where('id', $this->request->order_id)->value('tracking_number');

        if ($print_electronic_sheet_info['code'] == 200) {
            $route_code = $print_electronic_sheet_info['data'][0]['routeCode'];
            if ($route_code) {
                // $deliver_address['tel'] = LibBookModel::disTel($deliver_address['tel']);
                // $take_address['tel'] = LibBookModel::disTel($take_address['tel']);
                return $this->returnApi(200, '获取成功', true, [
                    'route_code' => $route_code,
                    'tracking_number' => $tracking_number,
                    'deliver_address' => $deliver_address,
                    'take_address' => $take_address,
                ]);
            } else {
                return $this->returnApi(202, '获取失败');
            }
        } else {
            return $this->returnApi(202, '获取失败');
        }
    }


    /**
     * 获取采购清单详情
     * @param purchase_id  采购清单id
     */
    public function purchaseDetail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('purchase_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->bookHomePurchaseModel->libDetail($this->request->purchase_id);
        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '暂无数据');
    }

    /**
     * 线下书籍归还列表（根据读者证号查询数据）
     * @param account 读者证号
     */
    public function getReaderBorrowList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('reader_borrow_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $userLibraryInfoModel = new UserLibraryInfo();
        //获取读者信息
        $account_info = $userLibraryInfoModel->where('account', $this->request->account)->first();

        if (empty($account_info)) {
            return $this->returnApi(202, '此读者证号信息不存在,请重新输入');
        }

        //获取馆藏书当前借阅信息
        $libApi = $this->getLibApiObj();
        $res = $libApi->getNowBorrowList($account_info['account'], 1, 100);

        $return_data = $this->bookHomePurchaseModel->getReturnIng($account_info['id']);

        $data = null;
        if ($res['code'] == 200) {
            if (empty($return_data)) {
                $return_data = [];
            }
            foreach ($res['content'] as $key => $val) {
                if (!in_array($val['barcode'], $return_data)) {
                    $val['return_state'] = 1;
                } else {
                    $val['return_state'] = 3;
                }
                $val['index'] = $this->addSerialNumberOne($key);
                $data[] = $val;
            }
        }
        //组装读者数据
        $account_info = $this->model->getReaderInfo($account_info);
        //获取读者当前借阅信息
        $result = $account_info;

        if (empty($data)) $data = [];
        //添加上用户失败的记录

        $result_not_library = $userLibraryInfoModel->getBorrowNotLibrary($this->request->account, true);

        $data = array_merge($data, $result_not_library);

        $result['borrow_list'] = $data;

        return $this->returnApi(200, '操作成功', true, $result);
    }

    /**
     * 线下书籍归还查询（根据条形码查询数据）
     * @param barcode 条形码
     */
    public function getBookBorrow()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('book_borrow')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        //获取馆藏书当前借阅信息
        $libApi = $this->getLibApiObj();
        $res = $libApi->getAssetByBarcode($this->request->barcode);

        if ($res['code'] == 200) {
            $data = $res['content'];
            $data['barcode'] = $this->request->barcode;
            $data['lib_name'] = config('other.lib_name');
            return $this->returnApi(200, '操作成功', true, $data);
        } else {
            //查询本地是否有借阅此书
            $res = $this->bookHomePurchaseModel->from($this->bookHomePurchaseModel->getTable() . ' as p')
                ->select('p.barcode', 'b.book_name', 'b.author', 'b.isbn', 'b.price', 'b.book_num', 'b.press', 'b.pre_time', 'b.intro')
                ->join('shop_book as b', 'b.id', '=', 'p.book_id')
                ->where('barcode', $this->request->barcode)
                ->where('node', 2)
                ->where('return_state', 1)
                ->first();

            if ($res) {
                $res['lib_name'] = config('other.lib_name');
                return $this->returnApi(200, '操作成功', true, $res);
            }
        }
        return $this->returnApi(202, '暂无借阅信息');
    }
    /**
     * 线下书籍确认归还  (新书的馆藏书的归还)
     * @param $barcode  条形码
     * @param $isbn    isbn号
     * @param $account 读者证号
     */
    public function offlineReturn()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('offline_return')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $barcode = $this->request->barcode;
        $isbn = $this->request->isbn;
        $account = $this->request->account;
        if (empty($barcode) && empty($isbn)) {
            return $this->returnApi(201, '参数错误');
        }
        //获取馆藏书当前借阅信息
        $libApi = $this->getLibApiObj();
        $res = $libApi->getNowBorrowList($this->request->account, 1, 100, $barcode);

        $account_id = UserLibraryInfo::where('account', $account)->value('id');
        //计算逾期金额
        $purchase_info = $this->bookHomePurchaseModel
            ->where(function ($query) use ($barcode, $isbn) {
                if (!empty($barcode)) {
                    $query->where('barcode', $barcode);
                } else {
                    $query->where('isbn', $isbn);
                }
            })
            //->where('return_state', 1)
            ->whereRaw('return_state =  1 or return_state = 3')
            ->where('account_id', $account_id)
            ->first();

        DB::beginTransaction();
        try {
            //添加书籍归还记录
            $returnRecordModelObj = new BookHomeReturnRecord();
            $returnRecordModelObj->account = $account;
            $returnRecordModelObj->account_id = $account_id;

            if (!empty($purchase_info)) {
                //从我们系统借出的书，包括失败的
                $purchase_info->return_time = date('Y-m-d H:i:s');
                $purchase_info->return_state = 2;

                $purchase_info->return_manage_id = request()->manage_id;
                $purchase_info->save();

                if ($purchase_info->type == 1) {
                    $book_info = ShopBook::find($purchase_info->book_id);
                } else {
                    $book_info = LibBook::find($purchase_info->book_id);
                }

                $returnRecordModelObj->book_name = $book_info->book_name;
                $returnRecordModelObj->author = $book_info->author;
                $returnRecordModelObj->price = $book_info->price;
                $returnRecordModelObj->book_num = $book_info->book_num;
                $returnRecordModelObj->isbn = $book_info->isbn;
                $returnRecordModelObj->barcode = $purchase_info->barcode;
                $returnRecordModelObj->press = $book_info->press;
                $returnRecordModelObj->pre_time = $book_info->pre_time;
                $returnRecordModelObj->borrow_time = $purchase_info->create_time;
                $returnRecordModelObj->expire_time = $purchase_info->expire_time;

                $book_name = $book_info->book_name;
            } else {
                if ($res['code'] !== 200) {
                    throw new Exception($res['msg']);
                }

                $returnRecordModelObj->book_name = $res['content'][0]['book_name'];
                $returnRecordModelObj->author = $res['content'][0]['author'];
                $returnRecordModelObj->price = $res['content'][0]['price'];
                $returnRecordModelObj->book_num = $res['content'][0]['book_num'];
                $returnRecordModelObj->isbn = $res['content'][0]['isbn'];
                $returnRecordModelObj->barcode = $res['content'][0]['barcode'];
                $returnRecordModelObj->press = $res['content'][0]['press'];
                //  $returnRecordModelObj->pre_time = $res['content'][0]['pre_time'];  //接口没返回
                $returnRecordModelObj->borrow_time = $res['content'][0]['borrow_time'];
                $returnRecordModelObj->expire_time = $res['content'][0]['expire_time'];

                $book_name = $res['content'][0]['book_name'];
            }
            $returnRecordModelObj->return_time = date('Y-m-d H:i:s');
            $returnRecordModelObj->return_manage_id = request()->manage_id;
            $returnRecordModelObj->save();

            $libApi = $this->getLibApiObj();
            //提交到外部接口 ， 如果是失败的数据，只管本地
            if (empty($purchase_info) || (!empty($purchase_info) && $purchase_info['node'] == 1)) {
                $status = 'h'; //h表示目前书籍处于借出状态
                //先查询是否在馆藏
                $asset_data = $libApi->getAssetByBarcode($barcode);
                if ($asset_data['code'] == 200) {
                    //查询到对应书籍信息并且获取书籍状态
                    $status = $asset_data['content']['status']; //书籍状态,b为可借。可借表示在藏，也就不用还书。
                }
                if ($status != 'b') {
                    //图书馆状态为不可借，再调用还书功能
                    $result = $libApi->bookReturn($barcode);
                    if ($result['code'] !== 200) {
                        throw new Exception($result['msg']);
                    }
                }

                // $result = $libApi->bookReturn($barcode);
                // if ($result['code'] !== 200) {
                //     throw new Exception($result['msg']);
                // }
            }

            if (!empty($purchase_info)) {
                //添加系统消息
                $this->systemAdd('线下归还成功', $purchase_info->user_id, $purchase_info->account_id, 43, null, "您之前借阅的书籍：《" . $book_name . "》，线下归还成功");

                //推送模板消息
                // $tempInfoObj = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($purchase_info->user_id);
                // $data['msg'] = '书籍归还成功！';

                // $data['book_name'] = $returnRecordModelObj->book_name;
                // $data['author'] = $returnRecordModelObj->author;
                // $data['return_time'] = $returnRecordModelObj->return_time;

                // $tempInfoObj->sendTempInfoReturnSuccess($data);
            }

            DB::commit();
            return $this->returnApi(200, '归还成功', true);
        } catch (\Exception $e) {
            // echo $e->getMessage();
            DB::rollBack();
            return $this->returnApi(202,  $e->getMessage());
        }
    }


    /**
     * 线下书籍直接确认归还 （涉及只有条形码，直接归还数据）
     * @param $barcode  条形码
     */
    public function offlineReturnDirect()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('offline_return_direct')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $barcode = $this->request->barcode;

        //获取馆藏书信息
        $libApi = $this->getLibApiObj();
        $res = $libApi->getAssetByBarcode($barcode);

        //查询本地是否有借阅此书
        $purchase_info = $this->bookHomePurchaseModel->getBorrowInfoByBarcode($barcode);
        if ($res['code'] !== 200 && empty($purchase_info)) {
            return $this->returnApi(202, $res['msg']);
        }

        $account = null;
        $account_id = null;
        if (!empty($purchase_info)) {
            $account_id = $purchase_info['account_id'];
            $account = UserLibraryInfo::where('id', $purchase_info['account_id'])->value('account');
        }

        DB::beginTransaction();
        try {
            //添加书籍归还记录
            $returnRecordModelObj = new BookHomeReturnRecord();
            $returnRecordModelObj->account = $account;
            $returnRecordModelObj->account_id = $account_id;

            if (!empty($purchase_info)) {
                //从我们系统借出的书，包括失败的
                $purchase_info->return_time = date('Y-m-d H:i:s');
                $purchase_info->return_state = 2;

                $purchase_info->return_manage_id = request()->manage_id;
                $purchase_info->save();

                //邮寄还书如果本书也在归还中，也改为已归还
                $post_return_data['status'] = 1;
                $post_return_data['change_time'] = date('Y-m-d H:i:s');
                BookHomePostalReturn::where('barcode', $purchase_info->barcode)->where('status', 3)->update($post_return_data);
            }

            $returnRecordModelObj->book_name = isset($res['content']['book_name']) ? $res['content']['book_name'] : $purchase_info['book_name'];
            $returnRecordModelObj->author = isset($res['content']['author']) ? $res['content']['author'] : $purchase_info['author'];
            $returnRecordModelObj->price = isset($res['content']['price']) ? $res['content']['price'] : $purchase_info['price'];
            $returnRecordModelObj->book_num = isset($res['content']['book_num']) ? $res['content']['book_num'] : $purchase_info['book_num'];
            $returnRecordModelObj->isbn = isset($res['content']['isbn']) ? $res['content']['isbn'] : $purchase_info['isbn'];
            $returnRecordModelObj->barcode = $barcode;
            $returnRecordModelObj->press = isset($res['content']['press']) ? $res['content']['press'] : $purchase_info['press'];
            $returnRecordModelObj->borrow_time = isset($purchase_info->create_time) ? $purchase_info->create_time : null;
            $returnRecordModelObj->expire_time = isset($purchase_info->expire_time) ? $purchase_info->expire_time : null;

            $returnRecordModelObj->return_time = date('Y-m-d H:i:s');
            $returnRecordModelObj->return_manage_id = request()->manage_id;
            $returnRecordModelObj->save();

            //提交到外部接口 ， 如果是失败的数据，只管本地
            if (empty($purchase_info) || (!empty($purchase_info) && $purchase_info['node'] == 1)) {
                // $status = 'h'; //h表示目前书籍处于借出状态
                // if ($res['code'] == 200) {
                //     //查询到对应书籍信息并且获取书籍状态
                //     $status = $res['content']['asset']['status']; //书籍状态,b为可借。可借表示在藏，也就不用还书。
                // }
                // if ($status != 'b') {
                //     //图书馆状态为不可借，再调用还书功能
                //     $result = $libApi->bookReturn($barcode);
                //     if ($result['code'] !== 200) {
                //         throw new Exception($result['msg']);
                //     }
                // }

                $result = $libApi->bookReturn($barcode);
                if ($result['code'] !== 200) {
                    throw new Exception($result['msg']);
                }
            }

            if (!empty($purchase_info)) {
                //添加系统消息
                $this->systemAdd('线下归还成功', $purchase_info->user_id, $purchase_info->account_id, 43, null, "您之前借阅的书籍：《" . $returnRecordModelObj->book_name . "》，线下归还成功");

                //推送模板消息
                // $tempInfoObj = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($purchase_info->user_id);
                // $data['msg'] = '书籍归还成功！';

                // $data['book_name'] = $returnRecordModelObj->book_name;
                // $data['author'] = $returnRecordModelObj->author;
                // $data['return_time'] = $returnRecordModelObj->return_time;

                // $tempInfoObj->sendTempInfoReturnSuccess($data);
            }

            DB::commit();
            return $this->returnApi(200, '归还成功', true);
        } catch (\Exception $e) {
            // echo $e->getMessage();
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }



    /**
     * 线上书籍归还
     * @param postal_id  邮递归还id
     * @param status 归还状态   1 确认归还  2 取消归还
     */
    public function onlineReturn()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('online_return')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $postal_id = $this->request->postal_id;
        $status = $this->request->status;
        $postal_info = BookHomePostalReturn::find($postal_id);

        if (empty($postal_info) || $postal_info['status'] != 3) {
            return $this->returnApi(202, '网络错误');
        }
        if (!empty($postal_info->purchase_id)) {
            $purchase_info = $this->bookHomePurchaseModel->find($postal_info->purchase_id);
            if (empty($purchase_info)) {
                return $this->returnApi(202, '网络错误');
            }
            if ($status == 1  &&  $purchase_info['return_state'] == 2) {
                return $this->returnApi(202, '系统检测到此数据已在其他渠道归还，请勿重复归还');
            }
        }

        $account = UserLibraryInfo::where('id', $postal_info['account_id'])->value('account');

        DB::beginTransaction();
        try {
            //修改状态
            $postal_info->change_time = date('Y-m-d H:i:s');
            $postal_info->status = $status;
            $postal_info->return_manage_id = request()->manage_id;
            $postal_info->save();

            $libApi = $this->getLibApiObj();

            if ($status == 1) {
                $bookHomeReturnRecordModel = new BookHomeReturnRecord();

                if (!empty($postal_info->purchase_id)) {
                    $purchase_info->return_state = 2;
                    $purchase_info->return_manage_id = request()->manage_id;
                    $purchase_info->save();

                    if ($purchase_info->type == 1) {
                        $book_info = ShopBook::find($purchase_info->book_id);
                    } else {
                        $book_info = LibBook::find($purchase_info->book_id);
                    }
                    $bookHomeReturnRecordModel->book_name = $book_info->book_name;
                    $bookHomeReturnRecordModel->author = $book_info->author;
                    $bookHomeReturnRecordModel->price = $book_info->price;
                    $bookHomeReturnRecordModel->book_num = $book_info->book_num;
                    $bookHomeReturnRecordModel->isbn = $book_info->isbn;
                    $bookHomeReturnRecordModel->barcode = $purchase_info->barcode;
                    $bookHomeReturnRecordModel->press = $book_info->press;
                    $bookHomeReturnRecordModel->pre_time = $book_info->pre_time;
                    $bookHomeReturnRecordModel->borrow_time = $purchase_info->create_time;
                    $bookHomeReturnRecordModel->expire_time = $purchase_info->expire_time;

                    $book_name = $book_info->book_name;
                } else {
                    //获取馆藏书当前借阅信息

                    $res = $libApi->getNowBorrowList($account, 1, 100, $postal_info['barcode']);
                    if ($res['code'] !== 200) {
                        throw new Exception($res['msg']);
                    }

                    $bookHomeReturnRecordModel->book_name = $res['content'][0]['book_name'];
                    $bookHomeReturnRecordModel->author = $res['content'][0]['author'];
                    $bookHomeReturnRecordModel->price = $res['content'][0]['price'];
                    $bookHomeReturnRecordModel->book_num = $res['content'][0]['book_num'];
                    $bookHomeReturnRecordModel->isbn = $res['content'][0]['isbn'];
                    $bookHomeReturnRecordModel->barcode = $res['content'][0]['barcode'];
                    $bookHomeReturnRecordModel->press = $res['content'][0]['press'];
                    $bookHomeReturnRecordModel->borrow_time = $res['content'][0]['borrow_time'];
                    $bookHomeReturnRecordModel->expire_time = $res['content'][0]['expire_time'];

                    $book_name = $res['content'][0]['book_name'];
                }

                $bookHomeReturnRecordModel->return_time = date('Y-m-d H:i:s');
                $bookHomeReturnRecordModel->return_manage_id = request()->manage_id;
                $bookHomeReturnRecordModel->save();


                $msg = '归还';
                $title = '邮递归还成功';
                $intro = "您借阅的书籍：《" . $book_name . "》 已邮递归还成功";
                $type = 43;
            } else {
                if (!empty($postal_info->purchase_id)) {
                    $purchase_info->return_state = 1;
                    $purchase_info->return_time = null;
                    $purchase_info->save();
                }
                $msg = '取消归还';
                $title = '邮递归还失败';
                $intro = "您借阅的书籍：《" . $postal_info->book_name . "》 邮递归还失败;如有疑问，请联系管理员处理";
                $type = 43;
            }

            //写入图书馆系统
            if ($status == 1 && ((empty($postal_info->purchase_id))  || (!empty($postal_info->purchase_id) && $purchase_info['node'] == 1))) {
                $result = $libApi->bookReturn($postal_info->barcode, $postal_info->create_time);
                if ($result['code'] !== 200) {
                    throw new Exception($result['msg']);
                }
            }

            //添加系统消息
            $this->systemAdd($title, $postal_info->user_id, $postal_info->account_id, $type, $postal_info->purchase_id, $intro);

            //添加推送模板消息
            if (config('other.is_send_wechat_temp_info')) {
                $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                $data['openid'] = UserWechatInfo::getOpenIdByUserId($postal_info->user_id);
                if ($status == 1) {
                    $data['msg'] = '书籍归还成功！';
                    $data['book_name'] = $bookHomeReturnRecordModel->book_name;
                    $data['author'] = $bookHomeReturnRecordModel->author;
                    $data['return_time'] = $bookHomeReturnRecordModel->return_time;
                    $tempInfoObj->sendTempInfoReturnSuccess($data);
                } else {
                    $data['username'] = UserLibraryInfo::where('id', $postal_info['account_id'])->value('username');
                    $data['msg'] = '书籍归还失败！';
                    $data['msg1'] = "书籍未收到或其他原因导致！";
                    $data['msg2'] = '您在线上申请归还的书籍，管理员审核失败，如有疑问，请联系管理员处理！';
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $tempInfoObj->sendTempInfoApplyReject($data);
                }
            }

            DB::commit();
            return $this->returnApi(200, $msg . '成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine() . '，操作失败');
        }
    }

    /**
     * 邮递还书列表
     * @param keywords_type  检索条件   0、全部  1、读者证号姓名  2、读者证号 3 条形码 4 快递单号  默认 0
     * @param keywords  检索条件
     * @param start_time 申请开始时间   数据格式    2020-05-12 12:00:00
     * @param end_time 申请结束时间     数据格式    2020-05-12 12:00:00
     * @param status  归还状态   1 已确认归还  2 已取消归还(管理员取消)  3 归还中  
     * @param page  页数，默认为1，
     * @param limit  条数，默认显示 10条
     */
    public function postalReturnList()
    {
        $keywords_type = $this->request->keywords_type;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $status = $this->request->status;
        $page = intval($this->request->page, 1) ?: 1;
        $limit = intval($this->request->limit, 10) ?: 10;

        $param = [
            'keywords_type' => $keywords_type,
            'keywords' => $keywords,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'status' => $status,
            'page' => $page,
            'limit' => $limit,
        ];
        $bookHomePostalReturnModel = new BookHomePostalReturn();
        $res = $bookHomePostalReturnModel->lists($param);
        if ($res['data']) {
            $courierNameModel = new CourierName();
            foreach ($res['data'] as $key => &$val) {
                //获取快递公司名称
                $res['data'][$key]['courier_name'] = $courierNameModel->where('id', $val['courier_id'])->value('name');

                if ($val['status'] == 3) {
                    //归还中
                    $postal_day = time_diff_day(strtotime($val['create_time']), time());
                } else {
                    $change_time = !empty($val['change_time']) ? strtotime($val['change_time']) : time();
                    $postal_day = time_diff_day(strtotime($val['create_time']), $change_time);
                }
                $res['data'][$key]['return_manage_name'] = !empty($val['return_manage_id']) ? Manage::getManageNameByManageId($val['return_manage_id']) : ''; //确认归还，无法归还操作人

                $res['data'][$key]['postal_day'] = $postal_day;
                $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            }
            $res = $this->disPageData($res);
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }



    /**
     * 管理员同意 和拒绝用户的 借阅申请（馆藏书）
     * @param order_ids  订单id  多个 , 逗号拼接
     * @param state   1 同意  2 拒绝
     * @param remark   拒绝理由
     */
    public function disposeOrderApply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('dispose_order_apply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $order_ids = $this->request->order_ids;
        $state = $this->request->state;
        $remark = $this->request->remark;

        $order_ids = explode(',', $order_ids);
        DB::beginTransaction();
        try {
            if ($state == 1) {
                $is_pay = 6;
                $title = '图书到家：审核通过';
                $intro = '您在线上申请的馆藏书借阅已通过';
            } else {
                $is_pay = 7;
                $title = '图书到家：审核未通过';
                $remarks = empty($remark) ? '' : ' 拒绝理由为：' . $remark;
                $intro = '您在线上申请的馆藏书借阅未通过;' . $remarks;
            }
            foreach ($order_ids as $key => $val) {
                $order_info = $this->model->find($val);
                if ($order_info['is_pay'] != 2) {
                    throw new Exception('订单号: ' . $order_info['order_number'] . " 数据处理失败");
                }
                $order_info->is_pay = $is_pay;
                $order_info->agree_time = date('Y-m-d H:i:s');
                $order_info->refund_remark = $remark;
                $order_info->save();

                /*if($state == 2){
                    $book_id_all = $newOrderBookModelObj->where('order_id' , $order_info['id'])->column('book_id');
                    //增加库存
                    foreach ($book_id_all as $v){
                        $res = NewBookModel::modifyRepertoryNumber($v  , 1);
                        if($res !== true){
                            throw new \Exception($res);
                        }
                    }
                }*/
                //添加系统消息
                $this->systemAdd($title, $order_info->user_id, $order_info->account_id, 41, $order_info->id, $intro);

                //审核拒绝推送模板消息
                if (config('other.is_send_wechat_temp_info')) {
                    if ($state == 2) {
                        //添加推送模板消息
                        // $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                        // $data['openid'] = UserWechatInfo::getOpenIdByUserId($order_info->user_id);
                        // $data['username'] = UserLibraryInfo::where('id', $order_info['account_id'])->value('username');
                        // $data['msg'] = '已拒绝';
                        // $data['msg1'] = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                        // $data['msg2'] = '您在线上申请的书籍，审核未通过，请重新申请其他书籍！';
                        // $data['create_time'] = date('Y-m-d H:i:s');
                        // $data['link'] = '?booktype=2&id=' . $order_info['id'];

                        // $tempInfoObj->sendTempInfoApplyReject($data);
                    }
                }

                if ($state == 2) {
                    //进行退款操作
                    $bookHomeOrderRefundModel = new BookHomeOrderRefund();
                    $bookHomeOrderRefundModel->refund($val, $remarks);
                }
            }
            DB::commit();
            return $this->returnApi(200, '处理成功', true);
        } catch (\Exception $e) {
            $msg = $e->getCode() == 202 ? $e->getMessage() : '处理失败';
            DB::rollBack();
            return $this->returnApi(202, $msg);
        }
    }

    /**
     * 确认发货或无法发货
     * @param state   1 确认发货  2 无法发货
     * @param order_id  订单id  只针对单个订单
     * @param username   收件人名称
     * @param tel   收件人电话
     * @param province   收件人省
     * @param city   收件人市
     * @param district   收件人区、县
     * @param street 街道
     * @param address   收件人详细地址
    //* @param tracking_number   确认发货 时必填 订单号
     * @param remark   拒绝理由
     * @param barcodes   缺少的书籍条形码 多个逗号拼接  （无法发货才填）
     */
    public function disposeOrderDeliver()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('dispose_order_deliver')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $order_id = $this->request->order_id;
        $state = $this->request->state;
        $username = $this->request->username;
        $tel = $this->request->tel;
        $province = $this->request->province;
        $city = $this->request->city;
        $district = $this->request->district;
        $street = $this->request->street;
        $address = $this->request->address;
        //$tracking_number = $this->request->tracking_number;
        $remark = $this->request->remark;
        $barcodes = $this->request->barcodes;
        if ($state == 1 && (empty($username) && empty($tel) && empty($province) && empty($city) && empty($district) && empty($street) && empty($address))) {
            return $this->returnApi(201, '参数错误');
        }
        if ($state == 1) {
            if (!verify_tel($tel)) {
                return $this->returnApi(201, '电话号码格式不正确');
            }
            /*检查是否合法地址*/
            $map = $this->getLonLatByAddress($province . $city . $district . $street . $address);

            if (isset($map['code']) && $map['code'] == 202) {
                return $this->returnApi(202, '收货地址有误，请填写正确地址');
            }
        }

        //获取发货地址信息
        $bookHomeReturnAddressModel = new BookHomeReturnAddress();
        $deliver_address = $bookHomeReturnAddressModel->getDeliverAddress(2);
        if (empty($deliver_address)) {
            return $this->returnApi(201, '发货信息未设置，请先设置');
        }

        DB::beginTransaction();
        try {
            $order_info = $this->model->find($order_id);
            if ($order_info['is_pay'] != 6) {
                throw new Exception('网络错误');
            }
            if (empty($order_info)) {
                throw new \Exception('暂无数据');
            }
            $book_info = $this->libBookBarcodeModel
                ->from($this->libBookBarcodeModel->getTable() . ' as b')
                ->select('b.*', 'l.book_name', 'l.author', 'l.isbn', 'l.price')
                ->join('book_home_order_book as o', 'o.barcode_id', '=', 'b.id')
                ->join('lib_book as l', 'l.id', '=', 'b.book_id')
                ->where('o.order_id', $order_id)
                ->get()
                ->toArray();

            $postalMsg = ''; //邮递失败的消息

            if ($state == 1) {
                //判断用户借阅权限
                $account = UserLibraryInfo::where('id', $order_info['account_id'])->value('account');
                $account_info['account_id'] = $order_info['account_id'];
                $account_info['account'] = $account;
                $this->libBookModel->checkNewBookBorrowAuth($account_info, $book_info, true);

                //修改订单地址
                $bookHomeOrderAddressModel = new BookHomeOrderAddress();
                $bookHomeOrderAddressModel->where('order_id', $order_id)
                    ->update([
                        'username' => $username,
                        'province' => $province,
                        'tel' => $tel,
                        'city' => $city,
                        'district' => $district,
                        'street' => $street,
                        'address' => $address,
                        'send_username' => $deliver_address['username'],
                        'send_province' => $deliver_address['province'],
                        'send_tel' => $deliver_address['tel'],
                        'send_city' => $deliver_address['city'],
                        'send_district' => $deliver_address['district'],
                        'send_street' => $deliver_address['street'],
                        'send_address' => $deliver_address['address'],
                        'manage_id' => request()->manage_id,
                        'change_time' => date('Y-m-d H:i:s'),
                    ]);

                $purchase_number = 0; //本次采购本书
                $purchase_money = 0; //本次采购金额
                // $flag = false;//标记状态，如果全部失败就都不成功，只要一个成功都成功

                $pushTempInfoData = []; //推送模板消息数据

                //先获取邮政订单号
                $postalObj = new Postal();
                //收货人地址
                $take_address = [
                    'username' => $username,
                    'tel' => $tel,
                    'province' => $province,
                    'city' => $city,
                    'district' => $district,
                    'street' => $street,
                    'address' => $address,
                ];

                if (config('other.is_write_postal')) {
                    $tracking_info = $postalObj->setOrder($order_id, $deliver_address, $take_address);

                    if ($tracking_info['code'] == 200) {
                        $tracking_number = $tracking_info['data']['waybill_no'];
                    } else {
                        //允许失败，失败后，手动下单
                        throw new Exception($tracking_info['msg']); //不允许失败
                        //$postalMsg = '快递下单失败，请再次手动下单';
                    }
                } else {
                    $tracking_number = null; //测试打开
                }

                $order_info->tracking_number = $tracking_number;
                $order_info->is_pay = 8;
                //获取邮政订单号end
                $libApi = $this->getLibApiObj();
                //写入文华系统
                foreach ($book_info as $key => $val) {
                    //书籍先写入,有可能成功，有可能失败
                    $res = $libApi->bookBorrow($account, $val['barcode']);
                    //不管失败成功都要写入用户记录
                    if ($res['code'] !== 200) {
                        // if($key === 0){
                        //throw new \Exception('数据处理失败');//第一个失败就全部失败
                        //throw new \Exception($res['msg']);//第一个失败就全部失败  不处理
                        // }
                        //修改条形码对应的记录为失败；
                        $this->bookHomeOrderBookModel->where('order_id', $order_id)->where('barcode_id', $val['id'])->update([
                            'node' => 2,
                            'change_time' => date('Y-m-d H:i:s'),
                        ]);
                        $where['node'] = 2;
                        $where['expire_time'] = date('Y-m-d H:i:s', strtotime("+1 month")); //默认一个月
                    } else {
                        //修改条形码对应的记录为失败；
                        $this->bookHomeOrderBookModel->where('order_id', $order_id)->where('barcode_id', $val['id'])->update([
                            'node' => 1,
                            'change_time' => date('Y-m-d H:i:s'),
                        ]);
                        $where['node'] = 1;
                        // $flag = true;

                        //TODO
                        $where['expire_time'] = $res['content']['returnDate'];
                    }

                    $where['create_time'] = date('Y-m-d H:i:s');
                    $where['return_state'] = 1;
                    $where['settle_state'] = 3;

                    $where['barcode'] = $val['barcode'];
                    $where['barcode_id'] = $val['id'];
                    $where['book_id'] = $val['book_id'];
                    $where['user_id'] = $order_info['user_id'];
                    $where['account_id'] = $order_info['account_id'];
                    // $where['shop_id'] = $order_info['shop_id'];
                    $where['order_id'] = $order_id;
                    $where['price'] = $val['price'];
                    $where['isbn'] = $val['isbn'];
                    $where['type'] = 2;
                    $where['pur_manage_id'] = request()->manage_id;


                    $pushTempInfoData[$key]['book_name'] = $val['book_name'];
                    $pushTempInfoData[$key]['author'] = $val['author'];
                    $pushTempInfoData[$key]['create_time'] = $where['create_time'];
                    $pushTempInfoData[$key]['expire_time'] = $where['expire_time'];

                    $purchase_number++;
                    $purchase_money += (float)$val['price'];
                    $this->bookHomePurchaseModel->insert($where);

                    //相应数据从书袋清除,馆藏书还可以再次借阅，新书不能
                    BookHomeSchoolbag::where('barcode_id', $val['id'])->where('type', 2)
                        ->where('user_id', $order_info['user_id'])->delete();
                }

                //修改用户借阅记录
                UserLibraryInfo::where('id', $order_info['account_id'])->update([
                    'purch_num_lib' => $purchase_number,
                    'purch_money_lib' => $purchase_money,
                ]);

                $title = '图书到家：已发货';
                $intro = '您在线上申请的馆藏书籍已发货，请及时关注邮递信息';

                // //添加推送模板消息
                // $tempInfoObj = new \app\common\controller\TempInfo();
                // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($order_info['user_id']);
                // $data['msg'] = '请随时关注邮递进度！';

                // foreach ($pushTempInfoData as $key => $val) {
                //     $data['book_name'] = $val['book_name'];
                //     $data['author'] = $val['author'];
                //     $data['create_time'] = $val['create_time'];
                //     $data['expire_time'] = $val['expire_time'];

                //     $tempInfoObj->sendTempInfoBorrowSuccess($data);
                // }
            } else {
                //缺少的书籍id
                $lack_book_msg = '';
                if (!empty($barcodes)) {
                    $barcodes = explode(',', $barcodes);
                    $barcodes_msg = '';
                    foreach ($barcodes as $val) {
                        $barcodes_msg .= ',' . '[' . $val . ']';
                    }
                    $lack_book_msg = trim($barcodes_msg, ',');
                }

                $order_info->is_pay = 9;
                $order_info->refund_remark = $remark . $lack_book_msg;
                //  $order_info->save();

                $title = '图书到家：发货失败';
                $remarks = empty($remark) ? '' : '失败原因：' . $remark . ';';
                $intro = '您在线上申请的馆藏书籍发货失败 ' . $remarks . $lack_book_msg;

                //添加推送模板消息
                if (config('other.is_send_wechat_temp_info')) {
                    $tempInfoObj = new \App\Http\Controllers\TempInfoController();
                    $data['openid'] = UserWechatInfo::getOpenIdByUserId($order_info['user_id']);
                    $data['username'] = UserLibraryInfo::where('id', $order_info['account_id'])->value('username');
                    $data['msg'] = $title;
                    $data['msg1'] = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                    $data['msg1'] =  $data['msg1'] . $lack_book_msg;
                    $data['msg2'] = '您在线上申请的馆藏书籍发货失败，请重新申请其他书籍！';
                    $data['create_time'] = date('Y-m-d H:i:s');

                    $data['link'] = '?booktype=2&id=' . $order_info['id'];
                    $tempInfoObj->sendTempInfoApplyReject($data);
                }

                //进行退款操作
                $msg = empty($remark) ? "书籍不存在或其他原因导致！" : $remark;
                $bookHomeOrderRefundModel = new BookHomeOrderRefund();
                $res = $bookHomeOrderRefundModel->refund($order_id, $msg);
            }
            $order_info->deliver_time = date('Y-m-d H:i:s');
            $order_info->deliver_manage_id = request()->manage_id;
            $order_info->save();

            //添加系统消息
            $system_id = $this->systemAdd($title, $order_info->user_id, $order_info->account_id, 42, $order_info->id, $intro);

            if ($state == 1) {
                //判断积分是否满足条件
                if (config('other.is_need_score') === true) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $order_info->user_id,  $order_info->account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) {
                        throw new Exception($score_status['msg']); //'积分不足无法参加活动'
                    } elseif ($score_status['code'] == 200) {
                        $scoreRuleObj->scoreChange($score_status, $order_info->user_id,  $order_info->account_id, $system_id); //添加积分消息
                    }
                }
            }

            DB::commit();
            return $this->returnApi(200, '处理成功' . $postalMsg, true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }


    /**
     * 获取书籍归还状态，修改本地书籍归还状态（外部 定时任务执行，可根据需求执行）
     */
    public function bookReturnState()
    {
        ini_set('max_execution_time', 3600);

        $res = $this->bookHomePurchaseModel->from($this->bookHomePurchaseModel->getTable() . ' as p')
            ->select('p.id', 'p.barcode', 'l.account', 'p.user_id')
            ->join('user_account_lib as l', 'l.id', '=', 'p.account_id')
            ->where('return_state', '<>', 2)
            ->get();

        $libApi = $this->getLibApiObj();
        foreach ($res as $key => $val) {
            if (empty($val['barcode'])) continue;
            $result = $libApi->getReturnData($val['account'], 1, 100, null, null, null, $val['barcode']);

            if ($result['code'] == 200) {
                //修改状态
                foreach ($result['content'] as $k => $v) {
                    //只有  Ea 和 Eb 是未还回状态
                    if ($v['event_type'] == 'Eg' || $v['event_type'] == 'Ec' || $v['event_type'] == 'Ed' || $v['event_type'] == 'Ef') {
                        $this->bookHomePurchaseModel->where('id', $val['id'])->update([
                            'return_state' => 2,
                            'return_time' => $v['return_time'],
                        ]);

                        //查看归还记录是否还有此书，如果有，也修改成已归还
                        BookHomePostalReturn::where('barcode', $val['barcode'])->where('status', 3)->update(['status' => 2, 'change_time' => $v['return_time']]);

                        //推送模板消息
                        // $tempInfoObj = new \app\common\controller\TempInfo();
                        // $data['openid'] = \app\common\controller\Common::getOpenIdByUserId($val['user_id']);
                        // $data['msg'] = '书籍归还成功！';

                        // $data['book_name'] = $v['book_name'];
                        // $data['author'] = $v['author'];
                        // $data['return_time'] = $v['return_time'];
                        // $tempInfoObj->sendTempInfoReturnSuccess($data);

                        break;
                    } elseif ($v['event_type'] == 'Ea') {
                        break;
                    }
                }
                // sleep(1);//间隔10秒
            }
        }
    }
}
